﻿using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using BookSleeve;
using RedisDemos.Extensions;

namespace RedisDemos.Scenarios
{
    public class Autocomplete : Scenario
    {
        protected override async Task Perform(RedisConnection conn)
        {
            await IndexNames(conn);

            "Index names done, wait 1 secs".LogInfo();
            await Task.Delay(TimeSpan.FromSeconds(1));

            var input = "ade";

            // ZRANK key member 
            var rank = await conn.SortedSets.Rank(Db, "autocomplete:names", input);
            if (rank.HasValue == false)
            {
                "No match for: {0}".LogInfo(input);
                return;
            }

            // ZRANGE key start stop [WITHSCORES] 
            var suggestions = await conn.SortedSets.RangeString(Db, "autocomplete:names", rank.Value + 1, rank.Value + 50 - 1);

            "Match for: {0}".LogInfo(input);
            suggestions.Where(s => s.Key.StartsWith(input) && s.Key.EndsWith("*"))
                .Select(s => s.Key.Substring(0, s.Key.Length - 1))
                .ForEach(s => s.LogInfo());
        }

        private async Task IndexNames(RedisConnection conn)
        {
            var names = File.ReadAllLines("female-names.txt")
                            .Where(l => l.StartsWith("#") == false);

            foreach (var name in names)
            {
                for (int i = 0; i < name.Length; i++)
                    // SADD key member [member ...] 
                    await conn.SortedSets.Add(Db, "autocomplete:names", name.Substring(0, i + 1), 0);

                // SADD key member [member ...] 
                await conn.SortedSets.Add(Db, "autocomplete:names", name + "*", 0);
            }
        }
    }
}
